<?php

namespace app\admin\controller;

use think\facade\Db;
use app\common\model\User;

class Admin extends Base
{

    protected $tb = "admin";

    /**
     * 查看
     */
    public function index()
    {
        // 判断管理员是不是超级管理
        $loginAdmin = session('adminSessionData');
        if ($loginAdmin['group_id'] == 1){
            $adminData = Db::name($this->tb)
            ->alias("a")
            ->join('auth_group b','a.group_id = b.id')
            ->field("a.*,b.title")
            ->order('a.id desc')->select(); 
        }else{
            $adminData = Db::name($this->tb)
            ->alias('a')
            ->join('auth_group b','a.group_id = b.id')
            ->field("a.*,b.title")
            ->where('a.id', $loginAdmin['id'])
            ->select();
        }
     
        return view('', [
            'tb' => $this->tb,
            'adminData' => $adminData,
        ]);
    }

    /**
     * 新增
     */
    public function add()
    {
        if (request()->isPost()) {
            $data = input('post.');
            if (!empty($data['password'])){
                $data['password'] = md5($this->salt.$data['password']);
            }
            $res = Db::name($this->tb)->insert($data);
            if ($res) {
                return alert('操作成功', 'index', 6);
            } else {
                return alert('操作失败', 'index', 5);
            }
        }
        $authGroup = Db::name("auth_group")->field('id,title')->select();
        return view('',[
            'authGroup' => $authGroup,
        ]);
    }

    /**
     * 编辑
     */
    public function edit()
    {
        if (request()->isPost()) {
            $data = input('post.');
            if (!empty($data['password'])){
                $data['password'] = $this->password_salt($data['password']);
            }else{
                unset($data['password']);
            }
            $res = Db::name($this->tb)->update($data);
            if ($res) {
                return alert('操作成功', 'index', 6);
            } else {
                return alert('操作失败', 'index', 5);
            }
        }
        $id = input('id');
        $authGroupData = Db::name("auth_group")->field('id,title')->select();
        $adminData = Db::name($this->tb)->where(['id'=>$id])->find();
        return view('',[
            'adminData' => $adminData,
            'authGroupData' => $authGroupData
        ]);
    }


}
